package com.year_23.may;

/**
 * @author: jsh
 * @create: 2023/5/22 23:21
 * @Description:    lc1234
 * @FileName: Day22_2
 * @History:
 * @自定义内容：
 */
public class Day22_2 {

    public static int balancedString(String  s) {
        int[] arr = new int[s.length()];
        int[] cns = new int[4];
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            arr[i] = c == 'W' ? 1 :  (c == 'E' ? 2 : (c == 'R' ? 3 : 0));
            cns[arr[i]]++;
        }
        int res = s.length();
        for (int i = 0, r = 0; i < s.length(); i++) {
            while (!ok(cns, i, r) && r < s.length()){
                cns[arr[r++]]--;
            }
            if (ok(cns, i, r)){
                res = Math.min(res, r-i);
            } else {
                break;
            }
            cns[arr[i]]++;
        }
        return res;
    }

    private static boolean ok(int[] cns, int i, int r) {
        int max = Math.max(Math.max(cns[0], cns[1]),Math.max(cns[2],cns[3]));

        int c = 4 * max- cns[0] - cns[1] - cns[2] -cns[3];
        int rest = r - i - c;
        return rest >=0 && rest % 4 == 0;
    }
}
